UICardChoice = UIBase.New(PanelNames.UICardChoice)

function UICardChoice:Init(curDeckIdx,isShowHero)
    self.curDeckIdx = curDeckIdx or 1
    self.isShowHero = isShowHero
end

function UICardChoice:OnCreate()
    self.btnBack = self:GetChild("Btn_Back")
    self.btnSave = self:GetChild("Btn_Save")
    self.listSaveCard = self:GetList("List_SaveCard")
    self.listChoiceCard = self:GetList("List_ChoiceCard")
    self.ctrlPage = self:GetController("Page")
    self.comCharactor = self:GetChild("Com_HeroCard")
    self.btnCharactor = self.comCharactor:GetChild("Btn_ChoiceCard")
    self.imgCharactor = self.comCharactor:GetChild("Com_Card"):GetChild("Loader_Draw")
    self.selectedHeroList = {}
    self.selectedCharactor = 0
    self.cfgHeroList = {}
    self.cfgCharactorList = {}
    self:AddEvent()
    self:InitView()
    self:Refresh()
end

function UICardChoice:AddEvent()
    self:RegisterOnClick(self.btnBack,self.OnClickBack)
    self:RegisterOnClick(self.btnSave,self.OnClickSave)
    self:RegisterOnClick(self.btnCharactor,self.OnClickCharactor)
    self:SetItemRenderer(self.listSaveCard,self.SaveCardItemRender, nil, true)
    self:SetItemRenderer(self.listChoiceCard,self.ChoiceCardItemRender, nil, true)
    self.ctrlPage.onChanged:Add(self.OnTabChanged,self)
    self.imgCharactor.onTouchBegin:Clear()
    self.imgCharactor.onTouchMove:Clear()
    self.imgCharactor.onTouchEnd:Clear()
    self.imgCharactor.draggable = false
    self.imgCharactor.draggable = true
    self.imgCharactor.onTouchBegin:Add(function()
        self.ctrlPage.selectedIndex = 0
    end)
    self.imgCharactor.onTouchEnd:Add(function()
        self:CharactorCardTouchEnd(self.imgCharactor)
        self:RefreshShowSaveBtn()
    end)
end

function UICardChoice:InitView()
    self.btnSave.visible = false
    local comCard = self.comCharactor:GetChild("Com_Card")
    local ctrlShowEnergy = comCard:GetController("fee")
    ctrlShowEnergy.selectedIndex = 1
    self.ctrlPage.selectedIndex = self.isShowHero and 1 or 0
    local cardList = decodeJsonStrToTable(GetPlayerPrefs("SelectedHeroList"..self.curDeckIdx))
    if cardList then
        self.selectedHeroList = {}
        for k,v in pairs(cardList) do
            if DataTable.GetById("t_hero",v) then
                table.insert(self.selectedHeroList,v)
            end
        end
    end
    self.selectedCharactor = decodeJsonStrToTable(GetPlayerPrefs("SelectedMainCharactor"..self.curDeckIdx))
    self.initSelectedHeroList = clone(self.selectedHeroList)
    self.initselectedCharactor = clone(self.selectedCharactor)
    self.selectedCharactorOrignalLocalPos = self.imgCharactor.position
end

function UICardChoice:Refresh()
    local heroCfg = DataTable.Get("t_hero")
    self.maxHeroCount = table.getn(heroCfg)
    self.cfgHeroList = {}
    self.cfgCharactorList = {}
    for k,v in pairs(heroCfg) do
        if v.f_CompanyType == Battle.ActorType.Hero and not table.ContainsValue(self.selectedHeroList, v.f_ID) then
            table.insert(self.cfgHeroList,v)
        elseif v.f_CompanyType == Battle.ActorType.Lord and not (v.f_ID == self.selectedCharactor) then
            table.insert(self.cfgCharactorList,v)
        end
    end
    table.sort(self.cfgHeroList, function(a,b)
        return a.f_ID < b.f_ID
    end)
    table.sort(self.cfgCharactorList, function(a,b)
        return a.f_ID < b.f_ID
    end)
    self.selectedCardItemList = {}
    self.listSaveCard.numItems = 8
    self.choiceCardItemList = {}
    if self.ctrlPage.selectedIndex == 0 then
        self.listChoiceCard.numItems = self.maxHeroCount
    elseif self.ctrlPage.selectedIndex == 1 then
        self.listChoiceCard.numItems = self.maxHeroCount
    end
    if self.choiceTimer ~= nil then
        UTimer.Remove(self.choiceTimer)
        self.choiceTimer = nil
    end
    self.choiceTimer = UTimer.TimeCall(function()
        self:SetChoiceCardItemOriginPosInfo()
    end, nil, 0.2, 1)
    if self.selectTimer ~= nil then
        UTimer.Remove(self.selectTimer)
        self.selectTimer = nil
    end
    self.selectTimer = UTimer.TimeCall(function()
        self:SetSelectedCardItemOriginPosInfo()
    end, nil, 0.2, 1)
    self:RefreshCharactorItemData()
end

function UICardChoice:RefreshCharactorItemData()
    local comCard = self.comCharactor:GetChild("Com_Card")
    local imgIcon = comCard:GetChild("Loader_Draw")
    local txtName = comCard:GetChild("Text_Name")
    local txtCost = comCard:GetChild("Text_CostNum")
    local ctrlEmpty = self.comCharactor:GetController("hasChoice")
    local data = self.selectedCharactor
    local cfg = DataTable.GetById("t_hero",data)
    if data and data ~= "" and cfg then
        ctrlEmpty.selectedIndex = 0
        imgIcon.url = IconUtil.GetHeroCardIconUrl(data)
        txtCost.text = tostring(cfg.f_ConsumeEnergy)
        txtName.text = cfg.f_HeroName
        self.comCharactor.onClick:Clear()
        self.comCharactor.onClick:Add(function()
            showUI(PanelNames.UIHeroDetails, data)
        end)
    else
        ctrlEmpty.selectedIndex = 1
    end
end

function UICardChoice:SaveCardItemRender(index, go)
    go.draggable = false
    local comCard = go:GetChild("Com_Card")
    local imgIcon = comCard:GetChild("Loader_Draw")
    local txtName = comCard:GetChild("Text_Name")
    local txtCost = comCard:GetChild("Text_CostNum")
    local ctrlEmpty = go:GetController("hasChoice")
    table.insert(self.selectedCardItemList, go)
    local data = self.selectedHeroList[index]
    if data then
        comCard.onTouchBegin:Clear()
        comCard.onTouchMove:Clear()
        comCard.onTouchEnd:Clear()
        comCard.draggable = false
        comCard.draggable = true
        comCard.onTouchBegin:Add(function()
            self.ctrlPage.selectedIndex = 1
        end)
        comCard.onTouchEnd:Add(function()
            self:SelectedCardTouchEnd(comCard, index, data)
            self:RefreshShowSaveBtn()
        end)
        ctrlEmpty.selectedIndex = 0
        local cfg = DataTable.GetById("t_hero",data)
        imgIcon.url = IconUtil.GetHeroCardIconUrl(data)
        txtCost.text = tostring(cfg.f_ConsumeEnergy)
        txtName.text = cfg.f_HeroName
        go.onClick:Clear()
        go.onClick:Add(function()
            showUI(PanelNames.UIHeroDetails, data)
        end)
    else
        ctrlEmpty.selectedIndex = 1
    end
end

function UICardChoice:ChoiceCardItemRender(index, go)
    local imgIcon = go:GetChild("Loader_Draw")
    local txtName = go:GetChild("Text_Name")
    local txtCost = go:GetChild("Text_CostNum")
    local ctrlShowName = go:GetController("showname")
    local ctrlShowEnergy = go:GetController("fee")
    table.insert(self.choiceCardItemList, go)
    local data
    if self.ctrlPage.selectedIndex == 0 then
        data = self.cfgCharactorList[index]
        ctrlShowEnergy.selectedIndex = 1
    else
        data = self.cfgHeroList[index]
        ctrlShowEnergy.selectedIndex = 0
    end
    go.onTouchBegin:Clear()
    go.onTouchMove:Clear()
    go.onTouchEnd:Clear()
    go.draggable = false
    go.draggable = true
    if data then
        go.visible = true
        ctrlShowName.selectedIndex = 1
        imgIcon.url = IconUtil.GetHeroCardIconUrl(data.f_ID)
        txtCost.text = tostring(data.f_ConsumeEnergy)
        txtName.text = data.f_HeroName
        go.onTouchBegin:Add(function()
        end)
        go.onTouchMove:Add(function()
        end)
        go.onTouchEnd:Add(function()
            self:ChoiceCardTouchEnd(go, index, data.f_ID)
            self:RefreshShowSaveBtn()
        end)
    else
        go.visible = false
        ctrlShowName.selectedIndex = 0
    end
    go.onClick:Clear()
    go.onClick:Add(function()
        showUI(PanelNames.UIHeroDetails, data.f_ID)
    end
    )
end

function UICardChoice:CharactorCardTouchEnd(obj)
    local isPlace = self:CheckPlaceSelectedCard(obj)
    if isPlace then
        self.selectedCharactor = 0
        self:Refresh()
    end
    self:SetSelectedCharactorItemPos()
end

function UICardChoice:SelectedCardTouchEnd(obj, originIndex, heroId)
    local isPlace = self:CheckPlaceSelectedCard(obj)
    if isPlace then
        for k,v in pairs(self.selectedHeroList) do
            if v == heroId then
                table.remove(self.selectedHeroList,k)
                self:Refresh()
            end
        end
    end
    self:SetSelectedCardItemPos(obj, originIndex)
end

function UICardChoice:ChoiceCardTouchEnd(obj, originIndex, heroId)
    if self.ctrlPage.selectedIndex == 0 then
        local isPlace = self:CheckPlaceChoiceCard(obj)
        if isPlace then
            self.selectedCharactor = heroId
            self:Refresh()
        end
    else
        local isPlace, index = self:CheckPlaceChoiceCard(obj)
        if isPlace then
            local data = self.selectedHeroList[index]
            if data then
                local tempId = data
                self.selectedHeroList[index] = heroId
                local heroData = DataTable.GetById("t_hero",tempId)
                self.cfgHeroList[originIndex] = heroData
            else
                table.insert(self.selectedHeroList,heroId)
            end
            self:Refresh()
        end
    end
    self:SetChoiceCardItemPos(obj, originIndex)
end

function UICardChoice:CheckPlaceChoiceCard(choiceCardObj)
    local gPoint = choiceCardObj:LocalToGlobal(Vector2(0, 0))
    local curPosX = gPoint.x
    local curPosY = gPoint.y
    if self.ctrlPage.selectedIndex == 0 then
        local comCard = self.comCharactor:GetChild("Com_Card")
        local comCardGlobalPos = comCard:LocalToGlobal(Vector2(0, 0))
        local isInRect = self:IsPointInRect(curPosX+(self.choiceCardItemList[1].width/2), curPosY+(self.choiceCardItemList[1].height/2), comCardGlobalPos, comCard.width, comCard.height)
        if isInRect then
            return true
        end
        return false
    else
        for i = 1,8 do
            local isInRect = self:IsPointInRect(curPosX+(self.choiceCardItemList[1].width/2), curPosY+(self.choiceCardItemList[1].height/2), self.selectedCardOrignalGlobalPosList[i], self.selectedCardItemList[i].width, self.selectedCardItemList[i].height)
            if isInRect then
                return true, i
            end
        end
        return false
    end
end

function UICardChoice:CheckPlaceSelectedCard(selectedCardObj)
    local gPoint = selectedCardObj:LocalToGlobal(Vector2(0, 0))
    local curPosX = gPoint.x
    local curPosY = gPoint.y
    local isInRect = self:IsPointInRect(curPosX+(self.selectedCardItemList[1].width/2), curPosY+(self.selectedCardItemList[1].height/2), self.choiceListGlobalPos, self.listChoiceCard.width, self.listChoiceCard.height)
    return isInRect
end

function UICardChoice:IsPointInRect(curPosX, curPosY, pos2, width, height)
    if curPosX >= pos2.x and curPosX <= pos2.x+width and curPosY >= pos2.y and curPosY <= pos2.y+height then
        return true
    end
    return false
end

function UICardChoice:SetChoiceCardItemOriginPosInfo()
    if not self.firstTime then
        self.firstTime = true
        self.chioceCardOrignalLocalPosList = {}
        self.chioceCardOrignalGlobalPosList = {}
        for k,v in ipairs(self.choiceCardItemList) do
            self.chioceCardOrignalLocalPosList[k] = v.position
            local tPos = {}
            local gPoint = v:LocalToGlobal(Vector2(0,0))
            tPos.x = gPoint.x
            tPos.y = gPoint.y
            tPos.z = 0
            self.chioceCardOrignalGlobalPosList[k] = tPos
        end
        self.choiceListGlobalPos = self.listChoiceCard:LocalToGlobal(Vector2(0,0))
    end
end

function UICardChoice:SetSelectedCardItemOriginPosInfo()
    if not self.firstTime1 then
        self.firstTime1 = true
        self.selectedCardOrignalLocalPosList = {}
        self.selectedCardOrignalGlobalPosList = {}
        self.selectedCardImgOrignalLocalPosList = {}
        for k,v in ipairs(self.selectedCardItemList) do
            self.selectedCardOrignalLocalPosList[k] = v.position
            self.selectedCardImgOrignalLocalPosList[k] = v:GetChild("Com_Card").position
            local tPos = {}
            local gPoint = v:LocalToGlobal(Vector2(0,0))--Util.FGUILocalToScreen(v,v.position.x,v.position.y,0,0)
            tPos.x = gPoint.x
            tPos.y = gPoint.y
            tPos.z = 0
            self.selectedCardOrignalGlobalPosList[k] = tPos
        end
    end
end

function UICardChoice:SetChoiceCardItemPos(obj, index)
    if obj and index and self.chioceCardOrignalLocalPosList and self.chioceCardOrignalLocalPosList[index] then
        obj.position = self.chioceCardOrignalLocalPosList[index]
    end
end

function UICardChoice:SetSelectedCardItemPos(obj, index)
    if obj and index and self.selectedCardImgOrignalLocalPosList and self.selectedCardImgOrignalLocalPosList[index] then
        obj.position = self.selectedCardImgOrignalLocalPosList[index]
    end
end

function UICardChoice:SetSelectedCharactorItemPos()
    self.imgCharactor.position = self.selectedCharactorOrignalLocalPos
end

function UICardChoice:OnTabChanged()
    if self.ctrlPage.selectedIndex == 0 then
        self.listChoiceCard.numItems = #self.cfgCharactorList
    elseif self.ctrlPage.selectedIndex == 1 then
        self.listChoiceCard.numItems = #self.cfgHeroList
    end
end

function UICardChoice:OnClickCharactor()
    if self.ctrlPage.selectedIndex == 1 then
        self.ctrlPage.selectedIndex = 0
    end
end

function UICardChoice:RefreshShowSaveBtn()
    local isShow = self:CheckShowSaveBtn()
    if isShow then
        self.btnSave.visible = true
    else
        self.btnSave.visible = false
    end
end

function UICardChoice:CheckShowSaveBtn()
    local selectCount = #self.selectedHeroList
    local initCount = #self.initSelectedHeroList
    if not (initCount == selectCount) then
        return true
    end
    for i =1, selectCount do
        if not (self.selectedHeroList[i] == self.initSelectedHeroList[i]) then
            return true
        end
    end
    if not (self.initselectedCharactor == self.selectedCharactor)then
        return true
    end
    return false
end

function UICardChoice:OnClickSave()
    SetPlayerPrefs("SelectedMainCharactor"..self.curDeckIdx,getJsonStr(self.selectedCharactor))
    SetPlayerPrefs("SelectedHeroList"..self.curDeckIdx,getJsonStr(self.selectedHeroList))
end

function UICardChoice:OnClickBack()
    FireEvent(UIEvent.FreshCardDeck)
    closeUI(PanelNames.UICardChoice)
end

return UICardChoice